/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package security;
import java.security.KeyPairGenerator;
import java.security.KeyPair;
import java.security.PublicKey;
import java.security.PrivateKey;
import javax.crypto.Cipher;
/**
 *
 * @author Comarch
 */
public class AsymmetricCipher {
    
    static String xform = "RSA";
    
    public static byte[] encrypt(byte[] inpBytes, PublicKey key,
      String xform) throws Exception {
    Cipher cipher = Cipher.getInstance(xform);
    cipher.init(Cipher.ENCRYPT_MODE, key);
    return cipher.doFinal(inpBytes);
  }
    
    public static byte[] encrypt(byte[] inpBytes, PublicKey key) throws Exception {
    return encrypt(inpBytes, key, xform);
  }
    
  public static byte[]  decrypt(byte[] inpBytes, PrivateKey key,
      String xform) throws Exception{
    Cipher cipher = Cipher.getInstance(xform);
    cipher.init(Cipher.DECRYPT_MODE, key);
    return cipher.doFinal(inpBytes);
  }
  
  public static byte[] decrypt(byte[] inpBytes, PrivateKey key) throws Exception{
    return decrypt(inpBytes, key, xform);
  }
  
  public static KeyPair getKeys(){
    try{
      KeyPairGenerator kpg = KeyPairGenerator.getInstance(xform);
    kpg.initialize(512*6); // 512 is the keysize.
    KeyPair kp = kpg.generateKeyPair();
    return kp;} catch(Exception e) {System.out.println("Key Error"+e); return null;}
  }

  public static void main(String[]args) throws Exception {
    
    // Generate a key-pair
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(512*4); // 512 is the keysize.
    KeyPair kp = kpg.generateKeyPair();
    PublicKey pubk = kp.getPublic();
    PrivateKey prvk = kp.getPrivate();

    byte[] dataBytes =
        "J".getBytes();

    byte[] encBytes = encrypt(dataBytes, pubk, xform);
   byte[] decBytes = decrypt(encBytes, prvk, xform);

    boolean expected = java.util.Arrays.equals(dataBytes, decBytes);
    System.out.println(new String(decBytes));
   
  }
}
